package com.woniu.adapter;

import com.woniu.outlet.mysql.dao.DailyIncomeDao;
import com.woniu.outlet.mysql.po.DailyCodeValuationMySQL;
import com.woniu.outlet.mysql.po.DailyIncomeMySQL;
import com.woniu.outlet.mysql.po.DailyIncomeMySQLExample;
import com.woniu.outlet.mysql.po.PersonalIncomeMySQL;
import com.woniu.outlet.redis.CodeOneRedisDao;
import com.woniu.outlet.redis.CodeTwoRedisDao;
import com.woniu.outlet.redis.po.DailyCodeTOne;
import com.woniu.outlet.redis.po.DailyCodeTTwo;
import com.woniu.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import sun.rmi.runtime.Log;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.List;

/**
 * 每日收益更新表适配层
 */
@Component
@Transactional
@Slf4j
public class DailyIncomeAdapter {

    @Autowired
    private DailyIncomeDao dao;

    @Autowired
    private PersonalIncomeAdapter personalIncomeAdapter;

    @Autowired
    private CodeOneRedisDao oneRedisDao;

    @Autowired
    private CodeTwoRedisDao twoRedisDao;


    public BigDecimal insert(PersonalIncomeMySQL p){
        String codeId = p.getCodeId();
        BigDecimal holdShare = p.getHoldShare();
        //得到昨日净值 T-1
        BigDecimal tv = oneRedisDao.findById(codeId).orElseThrow(NullPointerException::new).getTodayValuation();
        //得到T-2日净值
        BigDecimal yv = twoRedisDao.findById(codeId).orElseThrow(NullPointerException::new).getTodayValuation();
        //得到两日差值
        BigDecimal difference=tv.subtract(yv);
        //得到今日收益
        BigDecimal income=difference.multiply(holdShare);
        //保留两位小数
        BigDecimal todayIncome=income.divide(new BigDecimal("1"),2,BigDecimal.ROUND_DOWN);
        log.debug("今日用户id={},产品codeId={},收益为{}",p.getUserId(),p.getCodeId(),todayIncome);
        //判断是否有记录，没有就生成
        DailyIncomeMySQLExample example=new DailyIncomeMySQLExample();
        DailyIncomeMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andIncomeIdEqualTo(p.getUserId());
        criteria.andCodeIdEqualTo(codeId);
        criteria.andTodayDateEqualTo(DateUtil.getSendDate());
        List<DailyIncomeMySQL> ds = dao.selectByExample(example);
        if(ds.size()>0){
            log.debug("不生成记录");
            //收益进行累加
            DailyIncomeMySQL mySQL = ds.get(0);
            mySQL.setTodayIncome(mySQL.getTodayIncome().add(todayIncome));
            dao.updateByPrimaryKey(mySQL);
            log.debug("今日收益记录进行累加");
            return todayIncome;
        }
        DailyIncomeMySQL mySQL=DailyIncomeMySQL.builder()
                .incomeId(p.getUserId())
                .codeId(codeId)
                .todayDate(DateUtil.getSendDate())
                .yesterdayValuation(yv)
                .todayValuation(tv)
                .todayIncome(todayIncome)
                .status(0)
                .build();
        dao.insert(mySQL);
        log.debug("生成每日收益记录");
        return todayIncome;
    }

    public void updateIncome(Long userId, String codeId, BigDecimal totalIncome) {
        DailyIncomeMySQLExample example=new DailyIncomeMySQLExample();
        DailyIncomeMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIdEqualTo(codeId);
        criteria.andIncomeIdEqualTo(userId);
        List<DailyIncomeMySQL> d = dao.selectByExample(example);
        DailyIncomeMySQL mySQL = d.get(0);
        mySQL.setTodayIncome(totalIncome);
        dao.updateByPrimaryKey(mySQL);
        log.debug("userId={}，codeId={}，更新收益成功,今日{}收益为{}",userId,codeId,DateUtil.getSendDate(),totalIncome);
    }

    /**
     * 得到该基金的每日收益（收益明细）
     * @param userId
     * @param codeId
     * @return
     */
    public  List<DailyIncomeMySQL> getDailyIncome(Long userId, String codeId) {
        DailyIncomeMySQLExample example=new DailyIncomeMySQLExample();
        example.setOrderByClause("today_date desc");
        DailyIncomeMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIdEqualTo(codeId);
        criteria.andIncomeIdEqualTo(userId);
        return dao.selectByExample(example);
    }

    /**
     * 得到昨日收益
     * @param userId
     * @param codeId
     * @return
     */
    public BigDecimal getYesterdayIncome(Long userId, String codeId) {
        DailyIncomeMySQLExample example=new DailyIncomeMySQLExample();
        DailyIncomeMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIdEqualTo(codeId);
        criteria.andIncomeIdEqualTo(userId);
        String Yesterday = DateUtil.getUpdateBeforeTime(DateUtil.getYear(), DateUtil.getMonth(), DateUtil.getDayForNumber() - 1);
        criteria.andTodayDateEqualTo(Yesterday);
        List<DailyIncomeMySQL> ds = dao.selectByExample(example);
        if(ds.size()==0){
            return new BigDecimal("0");
        }
        return ds.get(0).getTodayIncome();
    }
}
